/**
 * 统一封装axios请求
 */
import axios from "axios";
import {Message} from "view-design";
import router from "@/router/index.js";
import {baseUrl} from "@/setting.js";
import Vue from "vue";



const QilinLoading=Vue.prototype.$QilinLoading;
// console.log(QilinLoading)

const service=axios.create({
    baseURL:baseUrl,
    timeout:10*1000
});
//请求拦截
service.interceptors.request.use((requestConfig)=>{
    // console.log(requestConfig); //请求配置项
    QilinLoading.show({
        text:"拼命加载中..."
    });
    // console.log(localStorage.token);
    if(localStorage.token){
        requestConfig.headers.Authorization="Bearer "+localStorage.token;
    };
    return requestConfig;
},(error)=>{
    return Promise.reject(error);
});

//响应拦截
service.interceptors.response.use((response)=>{
    // console.log(response); //响应数据体
    QilinLoading.hide();
    // console.log(response.data)
    if(response.data.code === 401){
        Message.error({
            content:"token失效，请重新登录!",
            background:true
        });
        localStorage.removeItem("token"); //清除token
        router.replace("/login");
    }else{
        return response.data;
    };
},(error)=>{
    console.log(error);
    QilinLoading.hide();
    if(error.response.status === 401){//此时属于token失效
        Message.error({
            message:"token失效，请重新登录!",
            center:true
        });
        localStorage.removeItem("token"); //清除token
        router.replace("/login");
    }else{
        if(!!error.response.data.message){
            Message.error({ //错误提醒
                message:error.response.data.message,
                center:true
            });
        }else{
            Message.error({
                message:"系统错误",
                center:true
            });
        };
    };
    return Promise.reject(error);
});

export default service;
